﻿using System;
using System.Collections;

namespace XYZShell.CsHelper.Reflection
{
    public class ObjectHelper
    {
        /// <summary>
        /// 设置对象属性的值
        /// </summary>
        /// <param name="obj">对象实例</param>
        /// <param name="propertyName">属性名</param>
        /// <param name="val">值</param>
        public void SetValue(object obj, string propertyName, object val)
        {
            SetValue(obj, propertyName, val, System.Reflection.BindingFlags.CreateInstance |
                 System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public);
        }
        /// <summary>
        ///  设置对象属性的值
        /// </summary>
        /// <param name="obj">对象实例</param>
        /// <param name="propertyName">属性名</param>
        /// <param name="val">值</param>
        /// <param name="bindingflag">指定属性筛选条件</param>
        public void SetValue(object obj, string propertyName, object val, System.Reflection.BindingFlags bindingflag)
        {
            Type type = obj.GetType();
            System.Reflection.PropertyInfo property = type.GetProperty(propertyName, bindingflag);
            if (property == null)
            {
                throw new Exception(string.Format("没有找到名为\"{0}\"的属性", propertyName));
            }
            property.SetValue(obj, val, null);
        }
        public object GetValue(object obj, string propertyName)
        {
            Type type = obj.GetType();
            System.Reflection.PropertyInfo prop = type.GetProperty(propertyName);
            if (prop==null)
            {
                throw new Exception(string.Format("没有找到名为\"{0}\"的属性", propertyName));
            }
            return prop.GetValue(obj, null);
        }

        public Hashtable GetClassPropertyDisplayNamesAndNames(Type clsType)
        {
            System.Reflection.PropertyInfo[] propertys = clsType.GetProperties();
            Hashtable hts = new Hashtable();
            for (int i = 0; i < propertys.Length; i++)
            {
                System.Reflection.PropertyInfo Pitem = propertys[i];
                object[] objs = Pitem.GetCustomAttributes(typeof(System.ComponentModel.DisplayNameAttribute), false);                
                if (objs == null || objs.Length == 0)
                {
                    hts.Add(Pitem.Name, "");
                }
                else
                {
                    foreach (object displayname in objs)
                    {
                        if (displayname is System.ComponentModel.DisplayNameAttribute)
                        {
                            System.ComponentModel.DisplayNameAttribute disname = displayname as System.ComponentModel.DisplayNameAttribute;
                            hts.Add(Pitem.Name,disname.DisplayName);
                        }
                    }
                }
            }
            return hts;
        }
    }
}
